﻿using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using TcpSocket;
using UnityEngine;

public class SocketServerManager : MonoBehaviour
{
    static TcpSocketServer TcpServer;

    public static string IP = "127.0.0.1";
    public static int Port = 10010;

    public static Dictionary<string, ClientInfo> ClientInfoDic = new Dictionary<string, ClientInfo>();

    private void Start()
    {
        TcpServer = new TcpSocketServer(IP, Port);
        TcpServer.Initialized();
        TcpServer.OnConnection += OnConnection;
        TcpServer.OnReceive += OnReceive;
        TcpServer.OnClientQuit += OnClientQuit;
        TcpServer.OnDisconnected += OnDisconnected;
        TcpServer.Connection();
    }

    /// <summary>
    /// 监听客户端连接
    /// </summary>
    /// <param name="info"></param>
    void OnConnection(ClientInfo info)
    {
        string msg = "客户端 " + info.id + " 加入会话!";
        Debug.Log(msg);
        Debug.Log(info.socket.RemoteEndPoint);
        OnSendAllMsg(msg);

        ClientInfoDic.Add(info.id, info);

        GameManager.Instence.AddDropdownOptionData(info.id);
    }

    /// <summary>
    /// 监听接收客户端消息
    /// </summary>
    /// <param name="info"></param>
    /// <param name="msg"></param>
    void OnReceive(ClientInfo info, string msg)
    {
        Debug.Log("接收到客户端 " + info.id + " 消息: " + msg);
        GameManager.Instence.textMessage= info.id + ": " + msg;
    }

    /// <summary>
    /// 监听客户端退出
    /// </summary>
    /// <param name="info"></param>
    void OnClientQuit(ClientInfo info)
    {
        Debug.Log("客户端 " + info.id + " 退出会话!");
        ClientInfoDic.Remove(info.id);
        GameManager.Instence.RemoveDropdownOptionData(info.id);
    }

    /// <summary>
    /// 服务器关闭
    /// </summary>
    void OnDisconnected()
    {
        Debug.Log("服务端关闭!");
    }

    /// <summary>
    /// 群发消息
    /// </summary>
    public static void OnSendAllMsg(string resMsg)
    {
        TcpServer.sendAllMsg(resMsg);
    }
    /// <summary>
    /// 发送消息给客户端
    /// </summary>
    /// <param name="socket"></param>
    /// <param name="resMsg"></param>
    public static bool OnSendToClient(string idName, string resMsg)
    {
        bool state = false;
        foreach (var client in ClientInfoDic)
        {
            if (idName == client.Value.id)
            {
                Socket socket = client.Value.socket;
                TcpServer.Send(socket, resMsg);
                state = true;
                break;
            }
        }
        return state;
    }

    private void OnDestroy()
    {
        if(TcpServer != null) TcpServer.Close();
    }

    private void OnApplicationQuit()
    {
        if(TcpServer != null) TcpServer.Close();
    }
}
